package com.lq.learningTest.duoxiancheng;

public class CasTest {

    public volatile static int COUNT = 0;

    //必须要保证这个方法的原子性所以加了synchronized
    public synchronized static boolean compareAndSwap(int expect, int update) {
        if (expect == COUNT) {
            COUNT = update;
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws InterruptedException {
        for (int j = 0; j < 100; j++) {
            new Thread(() -> {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                boolean flag = false;
                // 如果失败了就要不停的尝试
                while(!flag){
                    flag = compareAndSwap(COUNT, COUNT+1);
                }
            }).start();
        }
        Thread.sleep(1000);
        System.out.println(COUNT);
    }
}
